import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Req,
  Res,
  NotFoundException,
  Query,
  BadRequestException,
} from '@nestjs/common';
import { TagsService } from './tags.service';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';
import type { Tag } from 'src/typing';

@Controller()
export class TagsController {
  constructor(private readonly tagsService: TagsService) {}

  @Post()
  async createTag(@Req() req, @Res() res, @Body() createTagDto: CreateTagDto) {
    await this.tagsService.createTag(req.user.user_id, createTagDto);
    res.send({
      code: 0,
      msg: '创建成功',
    });
  }

  @Get()
  async filterAllTags(@Req() req, @Query() query) {
    const [tags, total] = await this.tagsService.filterAllTags({
      user_id: req.user.user_id,
      ...query,
    });
    return {
      list: tags,
      total,
    };
  }

  @Get(':tag_id')
  async getTag(@Param('tag_id') tag_id: string, @Req() req) {
    await this.tagsService.identifyAuth(req.user.user_id, +tag_id);
    const tagInfo = await this.tagsService.getTag(+tag_id);
    if (!tagInfo) {
      throw new NotFoundException('标签不存在');
    }
    return tagInfo;
  }

  @Patch(':tag_id')
  async updateTag(
    @Param('tag_id') tag_id: string,
    @Body() updateTagInfo: UpdateTagDto,
    @Req() req,
    @Res() res,
  ) {
    await this.tagsService.identifyAuth(req.user.user_id, +tag_id);
    await this.tagsService.updateTag(+tag_id, updateTagInfo);
    res.send({
      code: 0,
      msg: '修改成功',
    });
  }

  // 删除单个标签
  @Delete(':tag_id')
  async deleteTag(@Param('tag_id') tag_id: string, @Req() req, @Res() res) {
    await this.tagsService.identifyAuth(req.user.user_id, +tag_id);
    await this.tagsService.deleteTag(+tag_id);
    res.send({
      code: 0,
      msg: '删除成功',
    });
  }

  // 批量删除标签
  @Delete()
  async deleteTags(@Body() tags: Tag[], @Req() req, @Res() res) {
    try {
      for (const tag of tags) {
        await this.tagsService.identifyAuth(req.user.user_id, +tag.tag_id);
        await this.tagsService.deleteTag(+tag.tag_id);
      }
      res.send({
        code: 0,
        msg: '全部删除成功',
      });
    } catch (error) {
      throw new BadRequestException('批量删除失败，存在不能删除的标签');
    }
  }
}
